package com.estore.service;

import com.estore.model.Product;

import java.io.*;
import java.util.*;

public class ProductService {
    private final Map<Integer, Product> productMap = new LinkedHashMap<>();
    private String dataFilePath;

    public ProductService() {
        loadConfig();
        loadData();
    }

    private void loadConfig() {
        Properties props = new Properties();
        try (Reader r = new InputStreamReader(new FileInputStream("config.properties"), "UTF-8")) {
            props.load(r);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
        } catch (IOException e) {
            System.err.println("配置文件读取失败，使用默认路径 products.dat");
            dataFilePath = "products.dat";
        }
    }

    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productMap);
        } catch (IOException e) {
            System.err.println("保存数据失败：" + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) return;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            Map<Integer, Product> loaded = (Map<Integer, Product>) ois.readObject();
            productMap.clear();
            productMap.putAll(loaded);
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载数据失败：" + e.getMessage());
        }
    }

    /* ---------- 任务三：备份 ---------- */
    public void backupData() {
        String backupFile = dataFilePath + ".bak";
        try (FileInputStream fis = new FileInputStream(dataFilePath);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            System.out.println("备份完成 -> " + backupFile);
        } catch (IOException e) {
            System.err.println("备份失败：" + e.getMessage());
        }
    }

    public Collection<Product> listProducts() {
        return productMap.values();
    }

    public void addProduct(Product p) {
        productMap.put(p.getId(), p);
    }

    public void removeProduct(int id) {
        productMap.remove(id);
    }
}